let a1_edit
let a1_show
let a3_edit;
let a3_show;
let a4_edit;
let a4_show;

//橡皮檫标志
let erasureMode = false

let CAMERA_DEVICES_LIST = [];
let ACTIVE_CAMERA_INDEX = 0;
const VIDEO_INPUT = 'videoinput';
$(function () {
    a1_edit = buildFabricCanvas(document.getElementById('a1_edit'), "", "canvas1", 300, 300, false, false)
    a1_edit.isDrawingMode = true;
    a1_edit.freeDrawingBrush.color = "black";
    //这里一定是int，加了引号是个坑
    // a1_edit.freeDrawingBrush.width = "2";
    a1_edit.freeDrawingBrush.width = 2;

    a1_show = buildFabricCanvas(document.getElementById('a1_show'), "", "canvas1_1", 150, 150, false, false)

    bindThumbCanvasReloadEvent(a1_show, a1_edit);

    let a2_edit = buildFabricCanvas(document.getElementById('a2_edit'), "", "canvas2", 300, 300)
    let a2_show = buildFabricCanvas(document.getElementById('a2_show'), "", "canvas2_2", 150, 150)
    bindThumbCanvasReloadEvent(a2_show, a2_edit);
    addTextObjectToCanvas(a2_edit, "");


    a3_edit = buildFabricCanvas(document.getElementById('a3_edit'), "", "canvas3", 300, 300)
    a3_show = buildFabricCanvas(document.getElementById('a3_show'), "", "canvas3_3", 150, 150)
    bindThumbCanvasReloadEvent(a3_show, a3_edit);

    a4_edit = buildFabricCanvas(document.getElementById('a4_edit'), "", "canvas4", 300, 300)
    a4_show = buildFabricCanvas(document.getElementById('a4_show'), "", "canvas4_4", 150, 150)
    bindThumbCanvasReloadEvent(a4_show, a4_edit);
});

function upImage() {
    addImageToCanvas(a3_edit, a3_show);
}

function buildFabricCanvas(parentDivObject, svgBase64String, id, width, height, deleteFabricFlag, editableFlag) {
    //create canvas object instance
    let canvasObj = document.createElement("canvas");
    canvasObj.width = width;
    canvasObj.height = height;
    canvasObj.id = id;
    canvasObj.style.position = "absolute";
    canvasObj.style.zIndex = 0;
    parentDivObject.appendChild(canvasObj);
    if (!deleteFabricFlag) {
        parentDivObject.setAttribute("active_canvas_id", id);
    }
    canvasObj = new fabric.Canvas(canvasObj.id);
    canvasObj.hoverCursor = 'defaultCursor';

    //編集不可の場合、CanvasのdefaultCursorを「pointer」に設定する
    if (!editableFlag) {
        canvasObj.defaultCursor = "pointer";
    }

    fabric.isDrawingMode = false;
    //create empty canvas
    if (!svgBase64String) {
        return canvasObj;
    }

    if (svgBase64String.indexOf("<!DOCTYPE svg PUBLIC") > 0 || svgBase64String.indexOf("<svg") > 0) {
        loadCanvasFromSvgString(canvasObj, svgBase64String, width, height);
    } else {
        loadCanvasFromJsonString(canvasObj, svgBase64String, width, height);
    }

    //delete lower-canvase canvas object
    if (deleteFabricFlag) {
        let parentDiv = document.getElementById(id).parentElement;
        let parentParentNode = parentDiv.parentElement;
        let upperCanvas = parentDiv.getElementsByClassName("upper-canvas").item(0);
        let lowerCanvas = parentDiv.getElementsByClassName("lower-canvas").item(0);
        parentDiv.removeChild(upperCanvas);
        parentDiv.removeChild(lowerCanvas);
        parentParentNode.removeChild(parentDiv);
        parentParentNode.appendChild(lowerCanvas);
    }
    return canvasObj;
}

function updateThumbCanvas(editCanvas, thumbCanvas) {
    let svg = editCanvas.toJSON();
    thumbCanvas.clear();
    loadCanvasFromJsonString(thumbCanvas, svg);
}
function loadCanvasFromJsonString(canvasObj, jsonString, width, height) {
    let scale = 0.5
    try {
        canvasObj.loadFromJSON(jsonString, canvasObj.requestRenderAll.bind(canvasObj), function (o, item) {
            item.lockMovementX = true;
            item.lockMovementY = true;

            item.hasControls = false;
            item.hasBorders = false;
            item.splitByGrapheme = true;

        });
    } catch (e) {
        console.log(e);
    }

    canvasObj.setZoom(scale);
}


function bindThumbCanvasReloadEvent(thumbCanvas, editCanvas, editCanvasMap) {
    //  editCanvas.on('object:modified', (e) => {
    //    updateThumbCanvas();
    //  });
    //
    let TIME_OUT = 1000;
    editCanvas.on('object:added', function (e) {
        setTimeout(function () {
            updateThumbCanvas();
        }, TIME_OUT);
    });

    editCanvas.on('mouse:down', function (e) {
        textBoxIsEdit(editCanvas, true);
    });

    editCanvas.on('mouse:up', function (e) {
        let objects = thumbCanvas._objects;
        if (objects && objects.length > 0) {
            objects.some(function (element) {
                if (element.type === "path") {
                    setTimeout(function () {
                        updateThumbCanvas();
                    }, TIME_OUT);
                    return true;
                }
            });
        }
    });

    editCanvas.on('text:changed', function (opt) {
        updateThumbCanvas();
    });


    function updateThumbCanvas() {
        let svg = editCanvas.toJSON();
        console.log(svg);
        thumbCanvas.clear();
        loadCanvasFromJsonString(thumbCanvas, svg);
    }
}


function addTextObjectToCanvas(canvasObj, textStr) {
    let textObject = new fabric.Textbox(textStr, {
        id: "TEXT_AREA",
        left: 0,
        top: 0,
        fontSize: 21.3,
        lineHeight: 1.5,
        fontFamily: "bold NotoSansJP, meiryo, sans-serif",
        height: canvasObj.height,
        width: canvasObj.width,
        fixedHeight: canvasObj.height,
        // hasControls: true,
        borderColor: 'orange',
        // editingBorderColor: 'blue',
        // fill: "#000000",
        // selectable: false,
        lockMovementX: true,
        lockMovementY: true,
        hasControls: false,
        // editable: true,
        splitByGrapheme: true,
        hasBorders: false
    });

    canvasObj.add(textObject);
    canvasObj.setActiveObject(textObject);
    textObject.enterEditing();
    textObject.hiddenTextarea.focus();
}

function textBoxIsEdit(canDraw, isEdit) {
    if (canDraw.size() > 0) {
        canDraw.getObjects().forEach(function (item) {
            if (item.type === "textbox" && !item.readOnly) {
                if (isEdit) {
                    canDraw.setActiveObject(item);
                    // item.height = PARTS_GLOBAL_PARAMS.PARTS_EDIT_AREA_HEIGHT;
                    item.enterEditing();
                    item.hiddenTextarea.focus();
                }
                // else {
                //   // item.exitEditing();
                // }
                return;
            }
            else if (item.type === "textbox" && item.readOnly === true) {
                item.exitEditing();
                return;
            }
        })
    }
}

function addImageToCanvas(canvasObject, thumbCanvasObject, callableFunction) {
    let width = canvasObject.width;
    let height = canvasObject.height;

    let selectFile = selectFileDialog();
    selectFile.done(function (files) {
        canvasObject.clear();
        thumbCanvasObject.clear();
        let reader = new FileReader();
        reader.readAsDataURL(files[0]);
        let fileExt = files[0].name.toLowerCase();
        fileExt = fileExt.substring(fileExt.indexOf(".") + 1, fileExt.length);

        if (callableFunction) {
            callableFunction();
        }

        if (fileExt === "heic") {
            let blob = files[0];
            heic2any({
                blob: blob,
                toType: "image/jpeg",
                quality: 0.5
            })
                .then(function (resultBlob) {
                    let readerHeic = new FileReader();
                    readerHeic.readAsDataURL(resultBlob);
                    readerHeic.onload = function (event) {
                        loadImage(event.target.result, canvasObject, width, height);
                    };

                })
        } else {
            reader.onload = function (event) {
                loadImage(event.target.result, canvasObject, width, height);
            };
        }
    });
}

function selectFileDialog() {
    let promise = $.Deferred();
    let input = $("<input type='file' accept='image/png,image/jpeg' />");
    if (window.chrome) {
        input.change(function () {
            promise.resolve(this.files);
        });
        input.click();
    } else {
        input.click();

        let time = window.setInterval(function () {
            let files = input[0].files;
            if (files.length > 0) {
                promise.resolve(files);
                clearInterval(time);
            }
        }, 100);
    }
    //else if (isAppleOS()) {
    //  input.change(function (e) {
    //    promise.resolve(e.target.files);
    //  });
    //
    //  input.click();
    //} else
    return promise;
}


function loadImage(imageSrc, canvasObject, width, height) {
    let imgInfo = {
        quality: 0.5,
        width: 300,
        height: 300
    }
    imageCompression(imageSrc, imgInfo, function (base64Codes) {
        let img = new Image();
        img.setAttribute('crossOrigin', 'anonymous');
        img.src = base64Codes;
        img.onload = function () {
            let result = calculatePicture(img, width, height);

            let imgInstance = new fabric.Image(img, {
                left: result.startWidth,
                top: 0,

                width: result.originWidth,
                height: result.originHeight,
                // selectable: false
                lockMovementX: true,
                lockMovementY: true,
                hasControls: false,
                hasBorders: false
            });
            imgInstance.scale(result.scaleValue);

            canvasObject.add(imgInstance);
        };
    });
}

function imageCompression(path, obj, callback) {
    let img = new Image();
    img.src = path;
    img.onload = function () {
        let that = this;

        let w = that.width;
        let h = that.height;

        if (w < obj.width && h < obj.height) {
            callback(that.src);
            return;
        }

        let quality = 0.5; // 0.7

        let canvas = document.createElement('canvas');
        let ctx = canvas.getContext('2d');

        let anw = document.createAttribute('width');
        anw.nodeValue = w;
        let anh = document.createAttribute('height');
        anh.nodeValue = h;
        canvas.setAttributeNode(anw);
        canvas.setAttributeNode(anh);
        ctx.drawImage(that, 0, 0, w, h);

        if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
            quality = obj.quality;
        }

        let base64 = canvas.toDataURL('image/jpeg', quality)

        callback(base64);
    }
}

function calculatePicture(img, width, height) {
    let result = { startWidth: 0, originWidth: 0, originHeight: 0, scaleValue: 1 };
    result.originWidth = img.width;
    result.originHeight = img.height;
    result.scaleValue = 1;

    if (result.originWidth > width || result.originHeight > height) {
        if (height / result.originHeight > width / result.originWidth) {
            result.scaleValue = width / result.originWidth;
        } else {
            result.scaleValue = height / result.originHeight;
        }
    }
    result.startWidth = (width - img.width * result.scaleValue) / 2;
    return result;
}



function checkUserMedia() {
    // if (isIE11()) {
    //     return false;
    // }
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia || !navigator.mediaDevices.enumerateDevices) {
        return false;
    }
    return true;
}
function getCameraCount() {
    return CAMERA_DEVICES_LIST.length;
}
function getCameraList(callback) {
    if (!checkUserMedia()) {
        console.log("checked and return");
        return;
    }
    navigator.mediaDevices.enumerateDevices().then(function (devices) {
        if (getCameraCount() > 0) {
            callback();
            return;
        }
        devices.forEach(function (mediaDevice) {
            if (mediaDevice.kind === VIDEO_INPUT) {
                CAMERA_DEVICES_LIST.push(mediaDevice.deviceId);
            }
        });

        //デフォルトカメラが「１」に設定する
        if (CAMERA_DEVICES_LIST.length > 1) {
            ACTIVE_CAMERA_INDEX = 1;
        }
        if (CAMERA_DEVICES_LIST.length == 0) {
            console.log("没有摄像头");
        } else {
            callback();
        }
    }).catch(function (err) {
        console.log(err.name + ": " + err.message);
    });

}

function closeCamera() {
    if (window.stream) {
        window.stream.getTracks().forEach(function (track) {
            track.stop();
        });
    }
}
function cameraStart() {
    getCameraList(function () {
        openCamera($('#player')[0]);
    });
}
function getActiveCamera() {
    return CAMERA_DEVICES_LIST[ACTIVE_CAMERA_INDEX];
}
function openCamera(videoPlayerObject) {
    closeCamera();

    let currentCamera = getActiveCamera();
    let constraints = {
        video: { deviceId: currentCamera },
        audio: false
    };

    //let v = $('#player')[0];
    let promise = navigator.mediaDevices.getUserMedia(constraints);
    promise.then(function (stream) {
        // console.log("Fulfilled: " + stream);
        window.stream = stream;
        if ("srcObject" in videoPlayerObject) {
            videoPlayerObject.srcObject = stream;
        } else {
            videoPlayerObject.src = window.URL && window.URL.createObjectURL(stream) || stream;
        }

        videoPlayerObject.onloadedmetadata = function (e) {
            videoPlayerObject.play();
        };
    }, function (error) {
        console.log("Rejected: " + error);
    });
}



function cameraSave() {
    let videoPlayer = $('#player')[0];
    let videoCanvas = $('#canvas')[0];
    addCameraToCanvas(a4_edit, a4_show, videoPlayer, videoCanvas, function () {
        // a4_edit.isDrawingMode = false;
    });
}

function addCameraToCanvas(canvasObject, thumbCanvasObject, videoPlayerObject, videoCanvasObject, callableFunction) {
    let width = canvasObject.width;
    let height = canvasObject.height;

    canvasObject.clear();
    thumbCanvasObject.clear();

    if (callableFunction) {
        callableFunction();
    }
    videoCanvasObject.width = videoPlayerObject.videoWidth;
    videoCanvasObject.height = videoPlayerObject.videoHeight;
    videoCanvasObject.getContext('2d').drawImage(videoPlayerObject, 0, 0);
    let data = videoCanvasObject.toDataURL('image/png');
    loadImage(data, canvasObject, width, height);

    closeCamera();
}

function drawOn() {
    erasureMode = false;
    a1_edit.isDrawingMode = true;
    a1_edit.freeDrawingBrush.color = "black";
    a1_edit.freeDrawingBrush.width = 2;
}
function clearLittle() {

    a1_edit.isDrawingMode = true;
    a1_edit.freeDrawingBrush.color = "white";
    a1_edit.freeDrawingBrush.width = 16;

    //消しゴム
    //add by xumin  for #31734
    erasureMode = true;

    a1_edit.on("path:created", function (opt) {
        if (erasureMode) {
            opt.path.id = 'erasure';
            opt.path.globalCompositeOperation = "destination-out";
        } else {
            opt.path.id = '';
            opt.path.globalCompositeOperation = "source-over";
        }
        a1_edit.requestRenderAll();
    });
}

function clearAll() {
    a1_edit.clear();
    a1_show.clear();
}